<template>
    <el-dialog :draggable="true" v-model="dialogVisible" :width="'60%'" :title="dialogTitle"
        :close-on-click-modal="false" @close="handleClose">
        <el-form ref="enterpriseFormRef" :model="enterpriseForm" :rules="rules" label-width="120px" size="default"
            class="space-y-4">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="企业全称" prop="enterpriseName">
                        <el-input v-model="enterpriseForm.enterpriseName" placeholder="请输入企业全称" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="企业信用代码" prop="enterpriseCreditCode">
                        <el-input v-model="enterpriseForm.enterpriseCreditCode" placeholder="请输入企业信用代码"
                            maxlength="50" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="所属行业" prop="enterpriseIndustry">
                        <el-select v-model="enterpriseForm.enterpriseIndustry" placeholder="请选择所属行业" clearable>
                            <el-option v-for="item in EnterpriseConstants.industryOptions" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="企业类型" prop="enterpriseType">
                        <el-select v-model="enterpriseForm.enterpriseType" placeholder="请选择企业类型" clearable>
                            <el-option v-for="item in EnterpriseConstants.enterpriseTypeOptions" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="法定代表人" prop="enterpriseLegalRepresentative">
                        <el-input v-model="enterpriseForm.enterpriseLegalRepresentative" placeholder="请输入法定代表人"
                            maxlength="100" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="法人身份证号" prop="enterpriseLegalIdCard">
                        <el-input v-model="enterpriseForm.enterpriseLegalIdCard" placeholder="请输入法人身份证号"
                            maxlength="50" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="联系人" prop="enterpriseContactPerson">
                        <el-input v-model="enterpriseForm.enterpriseContactPerson" placeholder="请输入联系人"
                            maxlength="100" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联系人电话" prop="enterpriseContactPhone">
                        <el-input v-model="enterpriseForm.enterpriseContactPhone" placeholder="请输入联系人电话"
                            maxlength="50" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="联系人邮箱" prop="enterpriseContactEmail">
                        <el-input v-model="enterpriseForm.enterpriseContactEmail" placeholder="请输入联系人邮箱" type="email"
                            maxlength="100" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="注册日期" prop="enterpriseRegistDate">
                        <el-date-picker v-model="enterpriseForm.enterpriseRegistDate" type="date" placeholder="选择企业成立日期"
                            value-format="YYYY-MM-DD" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="注册资本" prop="enterpriseRegisteredCapital">
                        <el-input v-model.number="enterpriseForm.enterpriseRegisteredCapital" placeholder="请输入注册资本"
                            type="number" step="0.01" min="0" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="资本币种" prop="enterpriseCapitalCurrency">
                        <el-select v-model="enterpriseForm.enterpriseCapitalCurrency" placeholder="请选择资本币种">
                            <el-option label="人民币" value="人民币" />
                            <el-option label="美元" value="美元" />
                            <el-option label="欧元" value="欧元" />
                            <el-option label="英镑" value="英镑" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="状态" prop="enterpriseStatus">
                        <el-select v-model="enterpriseForm.enterpriseStatus" placeholder="请选择状态">
                            <el-option label="审核中" value="pending" />
                            <el-option label="已入驻" value="approved" />
                            <el-option label="已离园" value="moved_out" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="官网地址" prop="enterpriseOfficialWebsite">
                        <el-input v-model="enterpriseForm.enterpriseOfficialWebsite" placeholder="请输入官网地址"
                            maxlength="100" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="所属园区" prop="parkInfo">
                        <el-select v-model="enterpriseForm.parkInfo" placeholder="请选择所属行业" clearable value-key="id">
                            <el-option v-for="item in props.parkData" :key="item.id" :label="item.name" :value="item" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="是否关注">
                        <el-switch v-model="enterpriseForm.enterpriseIsFollowed" active-text="是" inactive-text="否" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="企业简介" prop="enterpriseIntro">
                        <el-input v-model="enterpriseForm.enterpriseIntro" placeholder="请输入企业简介" type="textarea"
                            :rows="4" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { EnterpriseConstants } from '../../enterprise/constant/EnterpriseConstant'

// 接收父组件参数
const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    enterprise: {
        type: Object,
        default: () => ({})
    },
    parkData: {
        type: Object,
        default: () => ([])
    }
});
const dialogVisible = ref(props.visible);
const emit = defineEmits(['close', 'save']);
const enterpriseFormRef = ref(null);
const dialogTitle = ref('新增企业');

// 表单数据
const enterpriseForm = reactive({
    enterpriseId: null,
    enterpriseName: '',//企业名称
    enterpriseCreditCode: '',//企业信用代码
    enterpriseIndustry: '',//所属行业
    enterpriseType: '',//企业类型
    enterpriseLegalRepresentative: '',//法定代表人
    enterpriseLegalIdCard: '',//法人身份证号
    enterpriseContactPerson: '',//联系人
    enterpriseContactPhone: '',//联系人电话
    enterpriseContactEmail: '',//联系人邮箱
    enterpriseRegistDate: '',//注册日期
    enterpriseRegisteredCapital: '',//注册资本
    enterpriseCapitalCurrency: '人民币',
    enterpriseIntro: '',//企业简介
    enterpriseOfficialWebsite: '',//官网地址
    enterpriseStatus: 'pending',//状态
    enterpriseIsFollowed: false,//是否关注
    isDeleted: null,//是否删除
    parkInfo: {},//园区信息
    parkBuilding: {},//楼栋信息
    enterpriseContractPojoList: [],//合同信息
    enterpriseRoomPojos: [],//绑定房间信息
    enterpriseQualificationPojos: []//资质信息
});
// 表单验证规则
const rules = {
    enterpriseName: [
        { required: true, message: '请输入企业全称', trigger: 'blur' },
        { max: 100, message: '企业全称不能超过100个字符', trigger: 'blur' }
    ],
    enterpriseLegalRepresentative: [
        { required: true, message: '请输入法定代表人', trigger: 'blur' },
        { max: 50, message: '法定代表人不能超过50个字符', trigger: 'blur' }
    ],
    enterpriseContactPerson: [
        { required: true, message: '请输入联系人', trigger: 'blur' },
        { max: 50, message: '入驻联系人不能超过50个字符', trigger: 'blur' }
    ],
    enterpriseContactPhone: [
        { required: true, message: '请输入联系人电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    enterpriseContactEmail: [
        { required: true, message: '请输入联系人邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    enterpriseRegistDate: [
        { required: true, message: '请选择企业成立日期', trigger: 'change' }
    ],
    parkInfo: [{ required: true, message: '请选择所属园区', trigger: 'change' }]
}

// 重置表单
const resetForm = () => {
      dialogTitle.value = '新增企业'
    if (enterpriseFormRef.value) {
        enterpriseFormRef.value.resetFields();
    }

    // 重置表单数据
    Object.keys(enterpriseForm).forEach(key => {
        if (key === 'enterpriseCapitalCurrency') {
            enterpriseForm[key] = '人民币';
        } else if (key === 'enterpriseStatus') {
            enterpriseForm[key] = 'pending';
        } else if (key === 'enterpriseIsFollowed') {
            enterpriseForm[key] = false;
        } else {
            enterpriseForm[key] = '';
        }
    });
}
// 关闭对话框
const handleClose = () => {
    resetForm();
    emit('close');
};
// 提交表单
const handleSubmit = async () => {
    try {
        await enterpriseFormRef.value.validate();
        // 处理日期格式，确保后端能正确解析
        validateAndSubmit();
        const formData = JSON.parse(JSON.stringify(enterpriseForm));
        // 提交数据给父组件处理
        emit('save', formData);
    } catch (error) {
        console.error('表单验证失败:', error);
        ElMessage.error('表单验证失败')
        return false;
    }
}
const validateAndSubmit = async () => {
    // 确保parkInfo是对象类型
    if (typeof enterpriseForm.parkInfo !== 'object' || enterpriseForm.parkInfo === null) {
        enterpriseForm.parkInfo = null;
    }
    if (typeof enterpriseForm.parkBuilding !== 'object' || enterpriseForm.parkBuilding === null) {
        enterpriseForm.parkBuilding = null;
    }
    if (typeof enterpriseForm.enterpriseContractPojoList !== 'object' || enterpriseForm.enterpriseContractPojoList === null) {
        enterpriseForm.enterpriseContractPojoList = null;
    }
    if (typeof enterpriseForm.enterpriseRoomPojos !== 'object' || enterpriseForm.enterpriseRoomPojos === null) {
        enterpriseForm.enterpriseRoomPojos = null;
    }
    if (typeof enterpriseForm.enterpriseQualificationPojos !== 'object' || enterpriseForm.enterpriseQualificationPojos === null) {
        enterpriseForm.enterpriseQualificationPojos = null;
    }
}

// 初始化表单数据
const initFormData = async (data) => {
    // 复制企业基本信息
    Object.keys(enterpriseForm).forEach(key => {
        if (key !== 'enterpriseRoomList' && data[key] !== undefined) {
            enterpriseForm[key] = data[key];
        }
    });
    if (enterpriseForm.enterpriseId) {
        dialogTitle.value = '企业编辑'
    } else {
        dialogTitle.value = '新增企业'
    }
}
// 监听visible变化
watch(
    () => props.visible,
    (newVal) => {
        dialogVisible.value = newVal;
    }
);

// 监听enterprise变化，初始化表单数据
watch(
    () => props.enterprise,
    (newVal) => {
        if (newVal && newVal.enterpriseId) {
            initFormData(newVal);
        } else if (newVal === null) {
            resetForm();
        }
    },
    { immediate: true }
);

</script>

<style scoped>
.space-y-4>.el-form-item {
    margin-bottom: 16px;
}
</style>